@model List<MVCWeekOne.Models.PlanDto>

@{
    ViewData["Title"] = "生产计划管理";
}

<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- FontAwesome图标 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />

<style>
    .plan-management {
        padding: 20px;
        background: #f5f7fa;
        min-height: 100vh;
    }

    .management-card {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        margin-bottom: 20px;
        overflow: hidden;
    }

    .card-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .card-header h2 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        display: flex;
        align-items: center;
    }

    .card-header .icon {
        font-size: 24px;
        margin-right: 10px;
    }

    .toolbar {
        padding: 20px;
        border-bottom: 1px solid #e8eaec;
        background: #fafbfc;
    }

    .search-box {
        display: flex;
        gap: 15px;
        align-items: center;
        flex-wrap: wrap;
    }

    .search-input {
        padding: 8px 15px;
        border: 1px solid #dcdee2;
        border-radius: 4px;
        font-size: 14px;
        min-width: 200px;
    }

    .btn {
        padding: 8px 20px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.3s;
    }

    .btn-primary {
        background: #5cadff;
        color: white;
    }

    .btn-success {
        background: #19be6b;
        color: white;
    }

    .btn-primary:hover {
        background: #348afe;
    }

    .btn-success:hover {
        background: #00a854;
    }

    .data-table {
        width: 100%;
        border-collapse: collapse;
        margin: 0;
    }

    .data-table thead {
        background: #f8f8f9;
    }

    .data-table th,
    .data-table td {
        padding: 12px 15px;
        text-align: left;
        border-bottom: 1px solid #e8eaec;
        font-size: 14px;
    }

    .data-table th {
        color: #515a6e;
        font-weight: 600;
        white-space: nowrap;
    }

    .data-table tbody tr {
        cursor: pointer;
        transition: background-color 0.3s;
    }

    .data-table tbody tr:hover {
        background: #f0f9ff;
    }

    .data-table tbody tr.selected {
        background: #e8f4fd;
        border-left: 3px solid #2d8cf0;
    }

    .status-badge {
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 500;
    }

    .status-active {
        background: #e1f5fe;
        color: #01579b;
    }

    .details-section {
        padding: 0;
        display: none;
    }

    .details-header {
        background: #f8f9fa;
        padding: 15px 20px;
        border-bottom: 1px solid #e8eaec;
        font-weight: 600;
        color: #495057;
    }

    .loading {
        text-align: center;
        padding: 40px 20px;
        color: #8c8c8c;
    }

    .loading i {
        font-size: 24px;
        animation: spin 1s linear infinite;
    }

    @@keyframes spin {
        0% {
            transform: rotate(0deg);
        }

        100% {
            transform: rotate(360deg);
        }
    }

    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #8c8c8c;
    }

    .empty-state i {
        font-size: 48px;
        margin-bottom: 15px;
        color: #d9d9d9;
    }

    .progress-bar {
        width: 100px;
        height: 6px;
        background: #f0f0f0;
        border-radius: 3px;
        overflow: hidden;
        display: inline-block;
    }

    .progress-fill {
        height: 100%;
        background: linear-gradient(90deg, #52c41a, #73d13d);
        border-radius: 3px;
        transition: width 0.3s;
    }

    /* 模态框样式 */
    .modal {
        position: fixed;
        top: 0;
        left: 0;
        z-index: 1055;
        display: none;
        width: 100%;
        height: 100%;
        overflow-x: hidden;
        overflow-y: auto;
        outline: 0;
        padding: 20px;
    }

    .modal.show {
        display: flex !important;
        align-items: center;
        justify-content: center;
    }

    .modal-backdrop {
        position: fixed;
        top: 0;
        left: 0;
        z-index: 1050;
        width: 100vw;
        height: 100vh;
        /* 稍微暗化背景，不使用模糊 */
        background-color: rgba(0, 0, 0, 0.15);
        /* 允许点击穿透到模态框 */
        pointer-events: none;
    }

    .modal-dialog {
        position: relative;
        width: auto;
        margin: 0.5rem;
        /* 允许模态框内部进行点击与交互 */
        pointer-events: auto;
    }

    .modal-lg {
        max-width: 900px;
    }

    @@media (min-width: 576px) {
        .modal-dialog {
            max-width: 500px;
            margin: 1.75rem auto;
        }

        .modal-lg {
            max-width: 900px;
        }
    }

    .modal-content {
        position: relative;
        display: flex;
        flex-direction: column;
        width: 100%;
        pointer-events: auto;
        background-color: #fff;
        background-clip: padding-box;
        border: 1px solid rgba(0, 0, 0, 0.2);
        border-radius: 0.5rem;
        outline: 0;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.4);
        animation: modalFadeIn 0.3s ease-out;
    }

    @@keyframes modalFadeIn {
        from {
            opacity: 0;
            transform: scale(0.8) translateY(-50px);
        }

        to {
            opacity: 1;
            transform: scale(1) translateY(0);
        }
    }

    .modal-header {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        padding: 1rem 1rem;
        border-bottom: 1px solid #dee2e6;
        border-top-left-radius: calc(0.3rem - 1px);
        border-top-right-radius: calc(0.3rem - 1px);
    }

    .modal-body {
        position: relative;
        flex: 1 1 auto;
        padding: 1rem;
    }

    .modal-footer {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        justify-content: flex-end;
        padding: 0.75rem;
        border-top: 1px solid #dee2e6;
        border-bottom-right-radius: calc(0.3rem - 1px);
        border-bottom-left-radius: calc(0.3rem - 1px);
    }

    .modal-footer>* {
        margin: 0.25rem;
    }

    .form-group label {
        font-weight: 600;
        color: #495057;
        margin-bottom: 5px;
    }

    .form-control-sm {
        padding: 4px 8px;
        font-size: 13px;
    }

    /* 编辑按钮样式 */
    .btn-outline-primary {
        border-color: #007bff;
        color: #007bff;
    }

    .btn-outline-primary:hover {
        background-color: #007bff;
        color: white;
    }

    .btn-sm {
        padding: 4px 8px;
        font-size: 12px;
        border-radius: 3px;
    }



    /* 表格行悬停效果 */
    .data-table tbody tr:hover .btn-outline-primary {
        opacity: 1;
        transform: scale(1.05);
        transition: all 0.2s;
    }

    /* 工具栏按钮样式 */
    .card-header .btn {
        margin-left: 10px;
    }

    .btn-info {
        background-color: #17a2b8;
        border-color: #17a2b8;
        color: white;
    }

    .btn-info:hover {
        background-color: #138496;
        border-color: #117a8b;
    }

    .btn-warning {
        background-color: #ffc107;
        border-color: #ffc107;
        color: #212529;
    }

    .btn-warning:hover {
        background-color: #e0a800;
        border-color: #d39e00;
    }

    .btn-secondary {
        background-color: #6c757d;
        border-color: #6c757d;
        color: white;
    }

    .btn-secondary:hover {
        background-color: #5a6268;
        border-color: #545b62;
    }

    .btn-danger {
        background-color: #dc3545;
        border-color: #dc3545;
        color: white;
    }

    .btn-danger:hover {
        background-color: #c82333;
        border-color: #bd2130;
    }

    .btn:disabled {
        opacity: 0.6;
        cursor: not-allowed;
    }

    /* Radio按钮样式优化 */
    input[type="radio"] {
        transform: scale(1.2);
        margin: 0;
        cursor: pointer;
    }

    /* 导入模态框样式 */
    .form-control-file {
        border: 1px solid #dcdee2;
        padding: 8px;
        border-radius: 4px;
        background-color: #fff;
    }

    .alert-info {
        background-color: #e7f3ff;
        border-color: #b6d7ff;
        color: #004085;
    }
</style>

<div class="plan-management">
    <!-- 生产计划列表 -->
    <div class="management-card">
        <div class="card-header">
            <h2>
                <span class="icon">📋</span>
                生产计划
            </h2>
            <div>
                <button class="btn btn-success" onclick="showCreateModal()">
                    <i class="fas fa-plus"></i> 新增
                </button>
                <button class="btn btn-info" onclick="exportPlans()">
                    <i class="fas fa-download"></i> 导出
                </button>
                <button class="btn btn-warning" onclick="showImportModal()">
                    <i class="fas fa-upload"></i> 导入
                </button>
                <button class="btn btn-secondary" onclick="downloadTemplate()">
                    <i class="fas fa-file-download"></i> 模板
                </button>
                <button class="btn btn-danger" onclick="deletePlan()" id="batchDeleteBtn" disabled>
                    <i class="fas fa-trash"></i> 删除
                </button>
            </div>
        </div>

        <div class="toolbar">
            <div class="search-box">
                <input type="text" class="search-input" placeholder="计划单号" id="planCodeSearch">
                <input type="text" class="search-input" placeholder="备注" id="remarkSearch">
                <input type="text" class="search-input" placeholder="创建人" id="createBySearch">
                <button class="btn btn-primary" onclick="searchPlans()">
                    <i class="fas fa-search"></i> 查询
                </button>
                <button class="btn" onclick="resetSearch()" style="background: #f7f7f7; color: #666;">
                    <i class="fas fa-redo"></i> 重置
                </button>
            </div>
        </div>

        <div style="overflow-x: auto;">
            <table class="data-table" id="planTable">
                <thead>
                    <tr>
                        <th style="width: 50px;">选择</th>
                        <th style="width: 60px;">序号</th>
                        <th>计划单号</th>
                        <th>备注</th>
                        <th>创建时间</th>
                        <th>创建人</th>
                        <th>修改人</th>
                        <th>修改时间</th>
                        <th style="width: 100px;">明细数量</th>
                        <th style="width: 100px;">状态</th>
                        <th style="width: 80px;">操作</th>
                    </tr>
                </thead>
                <tbody>
                    @if (Model != null && Model.Any())
                    {
                        @for (int i = 0; i < Model.Count; i++)
                        {
                            <tr onclick="selectPlan(@Model[i].Id, this)" data-plan-id="@Model[i].Id">
                                <td>
                                    <input type="radio" name="selectedPlan" class="plan-radio" value="@Model[i].Id"
                                        onclick="event.stopPropagation(); selectPlanRadio(@Model[i].Id, this);">
                                </td>
                                <td>@(i + 1)</td>
                                <td><a href="javascript:void(0)" onclick="openPlanModal(@Model[i].Id)"
                                        style="font-weight:600;">@Model[i].Code</a></td>
                                <td>@(Model[i].Remark ?? "-")</td>
                                <td>@Model[i].CreateTime.ToString("yyyy-MM-dd HH:mm:ss")</td>
                                <td>@(Model[i].CreateBy ?? "-")</td>
                                <td>@(Model[i].UpdateBy ?? "-")</td>
                                <td>@(Model[i].UpdateTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? "-")</td>
                                <td><span class="status-badge status-active">@Model[i].ItemCount</span></td>
                                <td><span class="status-badge status-active">启用</span></td>
                                <td>
                                    <button class="btn btn-sm btn-outline-primary"
                                        onclick="event.stopPropagation(); editPlan(@Model[i].Id)" title="编辑">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                </td>
                            </tr>
                        }
                    }
                    else
                    {
                        <tr>
                            <td colspan="11" class="empty-state">
                                <i class="fas fa-inbox"></i>
                                <div>暂无数据</div>
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    </div>

    <!-- 计划关联产品 -->
    <div class="management-card details-section" id="detailsSection">
        <div class="details-header">
            <span>📦 计划关联产品</span>
            <span id="selectedPlanInfo" style="margin-left: 20px; font-weight: normal; color: #666;"></span>
        </div>

        <div id="detailsContent">
            <div class="loading" id="detailsLoading">
                <i class="fas fa-spinner"></i>
                <div style="margin-top: 10px;">正在加载产品数据...</div>
            </div>
        </div>
    </div>
</div>

<!-- 新增生产计划模态框 -->
<div class="modal fade" id="createPlanModal" tabindex="-1" role="dialog" aria-labelledby="createPlanModalLabel"
    aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document" style="max-width: 900px;">
        <div class="modal-content">
            <div class="modal-header"
                style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                <h5 class="modal-title" id="createPlanModalLabel">
                    <i class="fas fa-plus-circle"></i> 新增生产计划
                </h5>
                <button type="button" class="close" onclick="closeCreateModal()" aria-label="Close"
                    style="color: white; opacity: 0.8;">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="createPlanForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="planCode"><i class="fas fa-barcode"></i> 计划单号 <span
                                        style="color: red;">*</span></label>
                                <input type="text" class="form-control" id="planCode" name="planCode"
                                    placeholder="请输入计划单号" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="remark"><i class="fas fa-comment"></i> 备注</label>
                                <input type="text" class="form-control" id="remark" name="remark" placeholder="请输入备注">
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label><i class="fas fa-list"></i> 关联产品</label>
                        <div style="margin-bottom: 10px;">
                            <button type="button" class="btn btn-sm btn-outline-primary" onclick="addPlanItem()">
                                <i class="fas fa-plus"></i> 添加产品
                            </button>
                        </div>
                        <div class="table-responsive">
                            <table class="table table-bordered table-sm" id="planItemsTable">
                                <thead class="thead-light">
                                    <tr>
                                        <th width="20%">产品编号 <span style="color: red;">*</span></th>
                                        <th width="25%">产品名称 <span style="color: red;">*</span></th>
                                        <th width="15%">规格</th>
                                        <th width="10%">单位</th>
                                        <th width="20%">生产人员</th>
                                        <th width="10%">操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- 动态添加的产品行 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeCreateModal()">
                    <i class="fas fa-times"></i> 取消
                </button>
                <button type="button" class="btn btn-success" onclick="savePlan()">
                    <i class="fas fa-save"></i> 保存
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 计划详情模态框（查看/编辑） -->
<div class="modal fade" id="planDetailModal" tabindex="-1" role="dialog" aria-labelledby="planDetailModalLabel"
    aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document" style="max-width: 1000px;">
        <div class="modal-content">
            <div class="modal-header"
                style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                <h5 class="modal-title" id="planDetailModalLabel">
                    <i class="fas fa-file-alt"></i> 计划详情
                </h5>
                <button type="button" class="close" onclick="closePlanModal()" aria-label="Close"
                    style="color: white; opacity: 0.8;">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="modalPlanId" />
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="modalPlanCode"><i class="fas fa-barcode"></i> 计划单号</label>
                            <input type="text" class="form-control" id="modalPlanCode" readonly />
                        </div>
                    </div>
                    <div class="col-md-8">
                        <div class="form-group">
                            <label for="modalRemark"><i class="fas fa-comment"></i> 备注</label>
                            <input type="text" class="form-control" id="modalRemark" />
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:10px;">
                        <label style="margin:0;"><i class="fas fa-list"></i> 关联产品</label>
                        <div>
                            <button type="button" class="btn btn-sm btn-outline-primary" onclick="addModalItemRow()">
                                <i class="fas fa-plus"></i> 添加产品
                            </button>
                        </div>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-bordered table-sm" id="modalPlanItemsTable">
                            <thead class="thead-light">
                                <tr>
                                    <th width="20%">产品编号</th>
                                    <th width="25%">产品名称</th>
                                    <th width="15%">规格</th>
                                    <th width="10%">单位</th>
                                    <th width="20%">生产人员</th>
                                    <th width="10%">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closePlanModal()">
                    <i class="fas fa-times"></i> 关闭
                </button>
                <button type="button" class="btn btn-success" onclick="savePlanModal()">
                    <i class="fas fa-save"></i> 保存
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 导入模态框 -->
<div class="modal fade" id="importModal" tabindex="-1" role="dialog" aria-labelledby="importModalLabel"
    aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header"
                style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white;">
                <h5 class="modal-title" id="importModalLabel">
                    <i class="fas fa-upload"></i> 导入生产计划
                </h5>
                <button type="button" class="close" onclick="closeImportModal()" aria-label="Close"
                    style="color: white; opacity: 0.8;">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="importForm" enctype="multipart/form-data">
                    <div class="form-group">
                        <label for="importFile"><i class="fas fa-file-excel"></i> 选择Excel文件</label>
                        <input type="file" class="form-control-file" id="importFile" accept=".xlsx,.xls" required>
                        <small class="form-text text-muted">支持 .xlsx 和 .xls 格式</small>
                    </div>
                    <div class="form-group">
                        <label for="operateBy"><i class="fas fa-user"></i> 操作人</label>
                        <input type="text" class="form-control" id="operateBy" value="系统管理员" required>
                    </div>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        <strong>导入提示：</strong>
                        <ul class="mb-0 mt-2">
                            <li>请确保Excel文件格式正确</li>
                            <li>可点击"模板"按钮下载标准模板</li>
                            <li>导入将会覆盖同名计划</li>
                        </ul>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeImportModal()">
                    <i class="fas fa-times"></i> 取消
                </button>
                <button type="button" class="btn btn-primary" onclick="downloadTemplate()">
                    <i class="fas fa-file-download"></i> 下载模板
                </button>
                <button type="button" class="btn btn-success" onclick="executeImport()">
                    <i class="fas fa-upload"></i> 开始导入
                </button>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.min.js"></script>

    <script>
        let selectedPlanId = null;
        let isEditMode = false; // 标记是否为编辑模式

        // 确保页面加载完成
        document.addEventListener('DOMContentLoaded', function () {
            console.log('页面加载完成，初始化功能...');
            console.log('jQuery可用:', typeof $ !== 'undefined');
            console.log('Bootstrap模态框可用:', typeof $ !== 'undefined' && $.fn && $.fn.modal);
        });

        // 选择生产计划（点击行）
        function selectPlan(planId, element) {
            // 选中对应的radio按钮
            const radio = element.querySelector('.plan-radio');
            if (radio) {
                radio.checked = true;
                selectPlanRadio(planId, radio);
            }
        }

        // 选择生产计划（点击radio按钮）
        function selectPlanRadio(planId, radioElement) {
            // 清除之前选中的行
            document.querySelectorAll('#planTable tbody tr').forEach(tr => {
                tr.classList.remove('selected');
            });

            // 选中当前行
            const row = radioElement.closest('tr');
            row.classList.add('selected');
            selectedPlanId = planId;

            // 显示明细区域
            showPlanDetails(planId, row);

            // 更新按钮状态
            updateButtonStates();
        }

        // 显示计划明细
        function showPlanDetails(planId, row) {
            document.getElementById('detailsSection').style.display = 'block';
            const planCode = row.children[2].textContent;
            document.getElementById('selectedPlanInfo').textContent = `计划单号: ${planCode}`;
            loadPlanDetails(planId);
        }

        // 更新按钮状态
        function updateButtonStates() {
            const batchDeleteBtn = document.getElementById('batchDeleteBtn');
            const exportBtn = document.querySelector('.btn-info'); // 导出按钮

            // 有选中项时启用按钮，否则禁用
            const hasSelection = selectedPlanId !== null;

            batchDeleteBtn.disabled = !hasSelection;
            if (exportBtn) exportBtn.disabled = !hasSelection;

            if (hasSelection) {
                batchDeleteBtn.innerHTML = `<i class="fas fa-trash"></i> 删除`;
            } else {
                batchDeleteBtn.innerHTML = `<i class="fas fa-trash"></i> 删除`;
            }
        }

        // 编辑生产计划
        function editPlan(planId) {
            isEditMode = true;
            selectedPlanId = planId;

            // 获取选中行的数据
            const row = document.querySelector(`tr[data-plan-id="${planId}"]`);
            if (!row) {
                alert('未找到计划数据');
                return;
            }

            const planCode = row.children[2].textContent.trim();
            const remark = row.children[3].textContent.trim();

            // 显示模态框并填充数据
            showEditModal(planId, planCode, remark === '-' ? '' : remark);
        }

        // 加载计划明细
        async function loadPlanDetails(planId) {
            const contentElement = document.getElementById('detailsContent');

            // 动态生成加载状态，保证多次点击时始终存在
            contentElement.innerHTML = `
                    <div class="loading">
                        <i class="fas fa-spinner"></i>
                        <div style="margin-top: 10px;">正在加载产品数据...</div>
                    </div>`;

            try {
                const response = await fetch(`/Plan/GetPlanDetail?planId=${planId}`);
                const result = await response.json();

                const items = (result && result.success && Array.isArray(result.items))
                    ? result.items
                    : (result && result.code === 200 && result.data && Array.isArray(result.data.items))
                        ? result.data.items
                        : null;

                if (items) {
                    renderPlanDetails(items);
                } else {
                    showError((result && (result.msg || result.message)) || '获取产品数据失败');
                }
            } catch (error) {
                console.error('Error loading plan details:', error);
                showError('网络请求失败，请检查网络连接');
            }
        }

        // 渲染计划产品表格
        function renderPlanDetails(items) {
            let html = `
                    <div style="overflow-x: auto;">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th style="width: 60px;">序号</th>
                                    <th>产品编码</th>
                                    <th>产品名称</th>
                                    <th>产品规格</th>
                                    <th>单位</th>
                                    <th>生产人员</th>
                                    <th>生产开始时间</th>
                                    <th>生产结束时间</th>
                                    <th>创建时间</th>
                                    <th>修改时间</th>
                                </tr>
                            </thead>
                            <tbody>`;

            if (items && items.length > 0) {
                items.forEach((item, index) => {
                    html += `
                            <tr>
                                <td>${index + 1}</td>
                                <td><strong>${item.productCode || '-'}</strong></td>
                                <td>${item.productName || '-'}</td>
                                <td>${item.spec || '-'}</td>
                                <td>${item.unit || '-'}</td>
                                <td>${item.producer || '-'}</td>
                                <td>${item.productionStartTime ? new Date(item.productionStartTime).toLocaleString('zh-CN') : '-'}</td>
                                <td>${item.productionEndTime ? new Date(item.productionEndTime).toLocaleString('zh-CN') : '-'}</td>
                                <td>${item.createTime ? new Date(item.createTime).toLocaleString('zh-CN') : '-'}</td>
                                <td>${item.updateTime ? new Date(item.updateTime).toLocaleString('zh-CN') : '-'}</td>
                            </tr>`;
                });
            } else {
                html += `
                        <tr>
                            <td colspan="10" class="empty-state">
                                <i class="fas fa-box-open"></i>
                                <div>该计划暂无关联产品</div>
                            </td>
                        </tr>`;
            }

            html += `
                            </tbody>
                        </table>
                    </div>`;

            document.getElementById('detailsContent').innerHTML = html;
        }

        // 显示错误信息
        function showError(message) {
            document.getElementById('detailsContent').innerHTML = `
                    <div class="empty-state" style="color: #f56c6c;">
                        <i class="fas fa-exclamation-triangle"></i>
                        <div>${message}</div>
                    </div>`;
        }

        // 搜索功能
        function searchPlans() {
            // 这里可以添加搜索逻辑
            console.log('执行搜索...');
        }

        // 重置搜索
        function resetSearch() {
            document.getElementById('planCodeSearch').value = '';
            document.getElementById('remarkSearch').value = '';
            document.getElementById('createBySearch').value = '';
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function () {
            // 如果有数据，默认选中第一行
            const firstRow = document.querySelector('#planTable tbody tr:first-child');
            if (firstRow && firstRow.dataset.planId) {
                const radio = firstRow.querySelector('.plan-radio');
                if (radio) {
                    radio.checked = true;
                    selectPlanRadio(parseInt(firstRow.dataset.planId), radio);
                }
            }
        });

        // ====================== 导出功能 ======================
        // 导出生产计划
        async function exportPlans() {
            try {
                console.log('开始导出计划...');

                // 检查是否有选中的计划
                if (!selectedPlanId) {
                    alert('请选择要导出的计划');
                    return;
                }

                // 构建导出命令
                const exportCommand = {
                    planIds: [selectedPlanId],
                    operateBy: '系统管理员'
                };

                console.log('导出参数:', exportCommand);

                // 发送导出请求
                const response = await fetch('/Plan/Export', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(exportCommand)
                });

                if (response.ok) {
                    // 获取文件名
                    const disposition = response.headers.get('Content-Disposition');
                    let filename = `生产计划导出_${new Date().toISOString().slice(0, 10)}.xlsx`;
                    if (disposition) {
                        const matches = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(disposition);
                        if (matches != null && matches[1]) {
                            filename = matches[1].replace(/['"]/g, '');
                        }
                    }

                    // 下载文件
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);

                    console.log('导出成功');
                    alert('导出成功！');
                } else {
                    const errorText = await response.text();
                    console.error('导出失败:', errorText);
                    alert('导出失败：' + errorText);
                }
            } catch (error) {
                console.error('导出出错:', error);
                alert('导出失败：网络错误');
            }
        }

        // ====================== 导入功能 ======================
        // 显示导入模态框
        function showImportModal() {
            try {
                // 清理遗留的背景遮罩
                const existingBackdrops = document.querySelectorAll('.modal-backdrop, #modal-backdrop');
                existingBackdrops.forEach(el => el.remove());

                // 重置表单
                document.getElementById('importForm').reset();
                document.getElementById('operateBy').value = '系统管理员';

                const modal = document.getElementById('importModal');
                const backdrop = document.createElement('div');
                backdrop.className = 'modal-backdrop';
                backdrop.id = 'import-modal-backdrop';
                backdrop.style.backgroundColor = 'rgba(0, 0, 0, 0.4)';
                backdrop.style.zIndex = '1050';
                document.body.appendChild(backdrop);

                modal.style.display = 'flex';
                setTimeout(() => {
                    modal.classList.add('show');
                }, 10);

                document.body.style.overflow = 'hidden';
                document.body.classList.add('modal-open');
                modal.style.zIndex = '1055';

                backdrop.onclick = function (event) {
                    if (event.target === backdrop) {
                        closeImportModal();
                    }
                };

                console.log('导入模态框显示完成');
            } catch (error) {
                console.error('显示导入模态框时出错:', error);
                alert('打开导入窗口失败：' + error.message);
            }
        }

        // 关闭导入模态框
        function closeImportModal() {
            try {
                const modal = document.getElementById('importModal');
                modal.style.display = 'none';
                modal.classList.remove('show');

                const backdrops = document.querySelectorAll('.modal-backdrop, #import-modal-backdrop');
                backdrops.forEach(el => el.remove());

                document.body.style.overflow = '';
                document.body.classList.remove('modal-open');

                console.log('导入模态框关闭完成');
            } catch (error) {
                console.error('关闭导入模态框时出错:', error);
            }
        }

        // 执行导入
        async function executeImport() {
            try {
                const fileInput = document.getElementById('importFile');
                const operateBy = document.getElementById('operateBy').value.trim();

                if (!fileInput.files || fileInput.files.length === 0) {
                    alert('请选择要导入的文件');
                    return;
                }

                if (!operateBy) {
                    alert('请输入操作人');
                    return;
                }

                const file = fileInput.files[0];

                // 检查文件类型
                const allowedExtensions = ['.xlsx', '.xls'];
                const fileExtension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
                if (!allowedExtensions.includes(fileExtension)) {
                    alert('只支持Excel文件格式(.xlsx, .xls)');
                    return;
                }

                // 构建FormData
                const formData = new FormData();
                formData.append('file', file);
                formData.append('operateBy', operateBy);

                // 显示进度
                const importBtn = document.querySelector('#importModal .btn-success');
                const originalText = importBtn.innerHTML;
                importBtn.disabled = true;
                importBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 导入中...';

                console.log('开始导入文件:', file.name);

                // 发送导入请求
                const response = await fetch('/Plan/Import', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();

                if (result.code === 200 || result.success) {
                    alert('导入成功！');
                    closeImportModal();
                    location.reload(); // 刷新页面显示最新数据
                } else {
                    alert('导入失败：' + (result.msg || result.message || '未知错误'));
                }
            } catch (error) {
                console.error('导入失败:', error);
                alert('导入失败：网络错误');
            } finally {
                // 恢复按钮
                const importBtn = document.querySelector('#importModal .btn-success');
                if (importBtn) {
                    importBtn.disabled = false;
                    importBtn.innerHTML = '<i class="fas fa-upload"></i> 开始导入';
                }
            }
        }

        // ====================== 模板下载功能 ======================
        // 下载导入模板
        async function downloadTemplate() {
            try {
                console.log('开始下载模板...');

                const response = await fetch('/Plan/ImportTemplate', {
                    method: 'GET'
                });

                if (response.ok) {
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = '生产计划导入模板.xlsx';
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);

                    console.log('模板下载成功');
                } else {
                    alert('模板下载失败');
                }
            } catch (error) {
                console.error('下载模板出错:', error);
                alert('下载模板失败：网络错误');
            }
        }

        // ====================== 删除功能 ======================
        // 删除生产计划
        async function deletePlan() {
            try {
                if (!selectedPlanId) {
                    alert('请选择要删除的计划');
                    return;
                }

                const confirmMessage = `确定要删除这个生产计划吗？此操作不可撤销！`;
                if (!confirm(confirmMessage)) {
                    return;
                }

                console.log('开始删除计划:', selectedPlanId);

                // 构建删除命令
                const deleteCommand = {
                    planIds: [selectedPlanId],
                    operateBy: '系统管理员'
                };

                // 禁用删除按钮
                const deleteBtn = document.getElementById('batchDeleteBtn');
                const originalText = deleteBtn.innerHTML;
                deleteBtn.disabled = true;
                deleteBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 删除中...';

                // 发送删除请求
                const response = await fetch('/Plan/BatchDelete', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(deleteCommand)
                });

                const result = await response.json();

                if (result.code === 200 || result.success) {
                    alert('删除成功！');
                    location.reload(); // 刷新页面
                } else {
                    alert('删除失败：' + (result.msg || result.message || '未知错误'));
                }
            } catch (error) {
                console.error('删除失败:', error);
                alert('删除失败：网络错误');
            } finally {
                // 恢复按钮
                const deleteBtn = document.getElementById('batchDeleteBtn');
                if (deleteBtn) {
                    deleteBtn.disabled = !selectedPlanId;
                    deleteBtn.innerHTML = '<i class="fas fa-trash"></i> 删除';
                }
            }
        }

        // 显示编辑模态框
        async function showEditModal(planId, planCode, remark) {
            try {
                isEditMode = true;
                selectedPlanId = planId;

                console.log('显示编辑模态框，计划ID:', planId);

                // 清理任何遗留的背景遮罩
                const existingBackdrops = document.querySelectorAll('.modal-backdrop, #modal-backdrop');
                existingBackdrops.forEach(el => el.remove());

                // 设置表单数据
                document.getElementById('planCode').value = planCode;
                document.getElementById('remark').value = remark;

                // 更新模态框标题
                document.getElementById('createPlanModalLabel').innerHTML = '<i class="fas fa-edit"></i> 编辑生产计划';

                // 清空明细表并加载现有明细
                const tbody = document.querySelector('#planItemsTable tbody');
                tbody.innerHTML = '';

                // 加载现有的计划明细
                await loadPlanItemsForEdit(planId);

                // 显示模态框
                const modal = document.getElementById('createPlanModal');
                const backdrop = document.createElement('div');
                backdrop.className = 'modal-backdrop';
                backdrop.id = 'create-modal-backdrop';
                backdrop.style.backgroundColor = 'rgba(0, 0, 0, 0.4)';
                backdrop.style.zIndex = '1050';
                document.body.appendChild(backdrop);

                modal.style.display = 'flex';
                setTimeout(() => {
                    modal.classList.add('show');
                }, 10);

                document.body.style.overflow = 'hidden';
                document.body.classList.add('modal-open');
                modal.style.zIndex = '1055';

                const modalContent = modal.querySelector('.modal-content');
                if (modalContent) {
                    modalContent.style.backgroundColor = '#ffffff !important';
                    modalContent.style.border = '3px solid #007bff';
                    modalContent.style.position = 'relative';
                    modalContent.style.zIndex = '1060';
                    modalContent.style.opacity = '1';
                    modalContent.style.pointerEvents = 'auto';
                    modalContent.style.transform = 'none';
                }

                modal.style.backgroundColor = 'transparent';
                modal.style.pointerEvents = 'auto';

                backdrop.onclick = function (event) {
                    if (event.target === backdrop) {
                        closeCreateModal();
                    }
                };

                const escKeyHandler = function (event) {
                    if (event.key === 'Escape') {
                        closeCreateModal();
                        document.removeEventListener('keydown', escKeyHandler);
                    }
                };
                document.addEventListener('keydown', escKeyHandler);

                console.log('编辑模态框显示完成');
            } catch (error) {
                console.error('显示编辑模态框时出错:', error);
                alert('打开编辑窗口失败：' + error.message);
            }
        }

        // 加载计划产品用于编辑
        async function loadPlanItemsForEdit(planId) {
            try {
                const response = await fetch(`/Plan/GetPlanDetail?planId=${planId}`);
                const result = await response.json();

                const tbody = document.querySelector('#planItemsTable tbody');

                // 处理不同的响应格式：MVC控制器返回 {success: true, items: [...]} 或后端API返回 {code: 200, data: {items: [...]}}
                const items = (result && result.success && Array.isArray(result.items))
                    ? result.items
                    : (result && result.code === 200 && result.data && Array.isArray(result.data.items))
                        ? result.data.items
                        : null;

                if (items && items.length > 0) {
                    items.forEach((item, index) => {
                        const row = document.createElement('tr');
                        row.dataset.itemId = item.id || item.Id || '';
                        row.innerHTML = `
                                <td>
                                    <input type="text" class="form-control form-control-sm" name="products[${index}].productCode" placeholder="产品编号" value="${item.productCode || ''}" required>
                                </td>
                                <td>
                                    <input type="text" class="form-control form-control-sm" name="products[${index}].productName" placeholder="产品名称" value="${item.productName || ''}" required>
                                </td>
                                <td>
                                    <input type="text" class="form-control form-control-sm" name="products[${index}].spec" placeholder="规格" value="${item.spec || ''}">
                                </td>
                                <td>
                                    <input type="text" class="form-control form-control-sm" name="products[${index}].unit" placeholder="单位" value="${item.unit || ''}">
                                </td>
                                <td>
                                    <input type="text" class="form-control form-control-sm" name="products[${index}].producer" placeholder="生产人员" value="${item.producer || ''}">
                                </td>
                                <td>
                                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="removePlanItem(this)">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </td>
                            `;
                        tbody.appendChild(row);
                    });
                    console.log(`加载了 ${items.length} 个产品到编辑表单`);
                } else {
                    console.log('没有找到产品数据，添加空白行');
                    // 如果没有产品，添加一行空白
                    addPlanItem();
                }
            } catch (error) {
                console.error('加载计划产品失败:', error);
                // 如果加载失败，至少添加一行空白
                addPlanItem();
            }
        }

        // 显示新增模态框
        function showCreateModal() {
            try {
                isEditMode = false;
                selectedPlanId = null;

                console.log('开始显示新增模态框...');

                // 清理任何遗留的背景遮罩
                const existingBackdrops = document.querySelectorAll('.modal-backdrop, #modal-backdrop');
                existingBackdrops.forEach(el => el.remove());

                // 清空表单
                document.getElementById('createPlanForm').reset();
                document.querySelector('#planItemsTable tbody').innerHTML = '';

                // 重置模态框标题
                document.getElementById('createPlanModalLabel').innerHTML = '<i class="fas fa-plus-circle"></i> 新增生产计划';

                // 添加一行默认的明细
                addPlanItem();

                const modal = document.getElementById('createPlanModal');

                // 创建背景遮罩
                const backdrop = document.createElement('div');
                backdrop.className = 'modal-backdrop';
                backdrop.id = 'create-modal-backdrop';
                backdrop.style.backgroundColor = 'rgba(0, 0, 0, 0.4)';
                backdrop.style.zIndex = '1050';
                document.body.appendChild(backdrop);

                // 显示模态框 - 分步骤执行以确保正确渲染
                modal.style.display = 'flex';

                // 使用setTimeout确保DOM渲染后再添加show类，触发动画
                setTimeout(() => {
                    modal.classList.add('show');
                }, 10);

                // 阻止body滚动
                document.body.style.overflow = 'hidden';
                document.body.classList.add('modal-open');

                // 确保模态框在最顶层
                modal.style.zIndex = '1055';

                // 给模态框内容添加明显的白色背景和强制样式
                const modalContent = modal.querySelector('.modal-content');
                if (modalContent) {
                    modalContent.style.backgroundColor = '#ffffff !important';
                    modalContent.style.border = '3px solid #007bff';
                    modalContent.style.position = 'relative';
                    modalContent.style.zIndex = '1060';
                    modalContent.style.opacity = '1';
                    modalContent.style.pointerEvents = 'auto';
                    modalContent.style.transform = 'none';
                }

                // 强制设置模态框本身的样式
                modal.style.backgroundColor = 'transparent';
                modal.style.pointerEvents = 'auto';

                // 添加点击背景关闭功能
                backdrop.onclick = function (event) {
                    if (event.target === backdrop) {
                        closeCreateModal();
                    }
                };

                // 添加ESC键关闭功能
                const escKeyHandler = function (event) {
                    if (event.key === 'Escape') {
                        closeCreateModal();
                        document.removeEventListener('keydown', escKeyHandler);
                    }
                };
                document.addEventListener('keydown', escKeyHandler);

                console.log('模态框显示完成');

                // 调试信息
                console.log('模态框状态检查:');
                console.log('模态框display:', modal.style.display);
                console.log('模态框z-index:', modal.style.zIndex);
                console.log('背景遮罩存在:', !!document.getElementById('create-modal-backdrop'));
                console.log('body overflow:', document.body.style.overflow);
            } catch (error) {
                console.error('显示模态框时出错:', error);
                alert('打开新增窗口失败：' + error.message);
            }
        }

        // 关闭模态框
        function closeCreateModal() {
            try {
                console.log('开始关闭模态框...');

                const modal = document.getElementById('createPlanModal');

                // 隐藏模态框
                modal.style.display = 'none';
                modal.classList.remove('show');

                // 移除所有背景遮罩
                const backdrops = document.querySelectorAll('.modal-backdrop, #modal-backdrop, #create-modal-backdrop');
                backdrops.forEach(el => el.remove());

                // 恢复body滚动
                document.body.style.overflow = '';
                document.body.classList.remove('modal-open');

                console.log('模态框关闭完成');
            } catch (error) {
                console.error('关闭模态框时出错:', error);
                // 强制关闭 - 确保清理所有相关元素
                const modal = document.getElementById('createPlanModal');
                if (modal) {
                    modal.style.display = 'none';
                    modal.classList.remove('show');
                }

                // 强制移除所有可能的背景遮罩
                const allBackdrops = document.querySelectorAll('.modal-backdrop, [id*="backdrop"], [id*="modal-backdrop"]');
                allBackdrops.forEach(el => el.remove());

                document.body.style.overflow = '';
                document.body.classList.remove('modal-open');
            }
        }

        // 添加计划产品行
        function addPlanItem() {
            const tbody = document.querySelector('#planItemsTable tbody');
            const rowIndex = tbody.children.length + 1;

            const row = document.createElement('tr');
            row.innerHTML = `
                    <td>
                        <input type="text" class="form-control form-control-sm" name="products[${rowIndex}].productCode" placeholder="产品编号" required>
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" name="products[${rowIndex}].productName" placeholder="产品名称" required>
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" name="products[${rowIndex}].spec" placeholder="规格">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" name="products[${rowIndex}].unit" placeholder="单位">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" name="products[${rowIndex}].producer" placeholder="生产人员">
                    </td>
                    <td>
                        <button type="button" class="btn btn-sm btn-outline-danger" onclick="removePlanItem(this)">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                `;

            tbody.appendChild(row);
        }

        // 删除计划产品行
        function removePlanItem(button) {
            const tbody = document.querySelector('#planItemsTable tbody');
            if (tbody.children.length > 1) {
                button.closest('tr').remove();
            } else {
                alert('至少需要保留一行产品数据');
            }
        }

        // 保存生产计划
        async function savePlan() {
            try {
                // 获取表单数据
                const planCode = document.getElementById('planCode').value.trim();
                const remark = document.getElementById('remark').value.trim();

                if (!planCode) {
                    alert('请输入计划单号');
                    return;
                }

                // 获取产品数据
                const products = [];
                const rows = document.querySelectorAll('#planItemsTable tbody tr');

                for (let row of rows) {
                    const productCode = row.querySelector('input[name*="productCode"]').value.trim();
                    const productName = row.querySelector('input[name*="productName"]').value.trim();
                    const spec = row.querySelector('input[name*="spec"]').value.trim();
                    const unit = row.querySelector('input[name*="unit"]').value.trim();
                    const producer = row.querySelector('input[name*="producer"]').value.trim();

                    if (!productCode || !productName) {
                        alert('请完整填写产品信息（产品编号、产品名称为必填项）');
                        return;
                    }

                    const today = new Date();
                    const tomorrow = new Date();
                    tomorrow.setDate(today.getDate() + 1);

                    products.push({
                        id: 0, // 新增产品时设置ID为0
                        productCode: productCode,
                        productName: productName,
                        spec: spec || null,
                        unit: unit || null,
                        producer: producer || null,
                        productionStartTime: today.toISOString(),
                        productionEndTime: tomorrow.toISOString(),
                        isRemoved: false
                    });
                }

                if (products.length === 0) {
                    alert('请至少添加一条产品数据');
                    return;
                }

                // 构建请求数据 - 根据模式包含或不包含ID
                const planData = {
                    code: planCode,
                    remark: remark || null,
                    operateBy: "系统管理员",
                    products: products
                };

                // 如果是编辑模式，添加ID
                if (isEditMode && selectedPlanId) {
                    planData.id = selectedPlanId;

                    // 为现有产品添加ID信息
                    const rows = document.querySelectorAll('#planItemsTable tbody tr');
                    const today = new Date();
                    const tomorrow = new Date();
                    tomorrow.setDate(today.getDate() + 1);

                    planData.products = planData.products.map((product, index) => {
                        const row = rows[index];
                        const productId = row && row.dataset.itemId ? parseInt(row.dataset.itemId) : 0;
                        return {
                            ...product,
                            id: productId,
                            productionStartTime: product.productionStartTime || today.toISOString(),
                            productionEndTime: product.productionEndTime || tomorrow.toISOString(),
                            isRemoved: false
                        };
                    });
                } else {
                    planData.id = 0;
                }

                // 禁用保存按钮，防止重复提交
                const saveButton = event.target;
                saveButton.disabled = true;
                saveButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';

                // 发送保存请求
                const response = await fetch('/Plan/SavePlan', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(planData)
                });

                const result = await response.json();

                if (result.code === 200 || result.success) {
                    const message = isEditMode ? '编辑成功！' : '新增成功！';
                    alert(message);
                    closeCreateModal();
                    // 刷新页面以显示新数据
                    location.reload();
                } else {
                    const message = isEditMode ? '编辑失败：' : '新增失败：';
                    alert(message + (result.msg || result.message || '未知错误'));
                }
            } catch (error) {
                console.error('保存失败:', error);
                alert('保存失败：网络错误');
            } finally {
                // 恢复保存按钮
                const saveButton = document.querySelector('#createPlanModal .btn-success');
                if (saveButton) {
                    saveButton.disabled = false;
                    saveButton.innerHTML = '<i class="fas fa-save"></i> 保存';
                }
            }
        }

        // 打开计划详情模态框并加载数据
        async function openPlanModal(planId) {
            try {
                // 清理可能残留的遮罩/状态，防止灰屏无法点击
                cleanupModalArtifacts();

                // 设置基础信息（从当前表格行读取，避免额外接口）
                const row = document.querySelector(`#planTable tbody tr[data-plan-id="${planId}"]`);
                const code = row ? row.children[1].textContent.trim() : '';
                const remark = row ? row.children[2].textContent.trim() : '';
                document.getElementById('modalPlanId').value = planId;
                document.getElementById('modalPlanCode').value = code;
                document.getElementById('modalRemark').value = (remark && remark !== '-') ? remark : '';

                // 清空明细区并先放一个占位加载行
                const tbody = document.querySelector('#modalPlanItemsTable tbody');
                tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">加载中...</td></tr>';

                // 显示模态框
                if (typeof $ !== 'undefined' && $.fn && $.fn.modal) {
                    // 将模态框移动到 body，确保层级正确
                    const modalEl = document.getElementById('planDetailModal');
                    if (modalEl && modalEl.parentElement !== document.body) {
                        document.body.appendChild(modalEl);
                    }
                    $('#planDetailModal').modal({ backdrop: true, keyboard: true, focus: true, show: true });
                } else {
                    const modal = document.getElementById('planDetailModal');
                    modal.style.display = 'block';
                    modal.classList.add('show');
                    document.body.classList.add('modal-open');
                }

                // 拉取产品数据
                const resp = await fetch(`/Plan/GetPlanDetail?planId=${planId}`);
                const result = await resp.json();

                tbody.innerHTML = '';

                // 处理不同的响应格式：MVC控制器返回 {success: true, items: [...]} 或后端API返回 {code: 200, data: {items: [...]}}
                const items = (result && result.success && Array.isArray(result.items))
                    ? result.items
                    : (result && result.code === 200 && result.data && Array.isArray(result.data.items))
                        ? result.data.items
                        : null;

                if (items && items.length > 0) {
                    items.forEach(item => addModalItemRow({ ...item, id: item.id || item.Id }));
                    console.log(`详情模态框加载了 ${items.length} 个产品`);
                } else {
                    console.log('详情模态框没有找到产品数据，添加空白行');
                    // 无产品时至少给一行空白可编辑
                    addModalItemRow();
                }

                // 再次清理一次错误的多余遮罩（某些浏览器可能重复生成）并校正层级
                fixModalZIndex();
            } catch (err) {
                console.error('打开计划详情失败:', err);
                alert('打开计划详情失败');
            }
        }

        // 关闭计划详情模态框
        function closePlanModal() {
            if (typeof $ !== 'undefined' && $.fn && $.fn.modal) {
                $('#planDetailModal').modal('hide');
            } else {
                const modal = document.getElementById('planDetailModal');
                modal.style.display = 'none';
                modal.classList.remove('show');
                document.body.classList.remove('modal-open');
            }
            // 保险：移除遗留遮罩
            setTimeout(() => cleanupModalArtifacts(), 50);
        }

        // 工具：清理遗留的遮罩/状态，防止灰屏
        function cleanupModalArtifacts() {
            try {
                const customBackdrop = document.getElementById('modal-backdrop');
                if (customBackdrop) customBackdrop.remove();
                document.querySelectorAll('.modal-backdrop').forEach(el => el.remove());
                document.body.classList.remove('modal-open');
                document.body.style.overflow = '';
            } catch (_) { }
        }

        // 工具：修正层级，确保弹窗在遮罩之上
        function fixModalZIndex() {
            try {
                const modal = document.getElementById('planDetailModal');
                if (modal) {
                    modal.style.zIndex = '1050';
                }
                document.querySelectorAll('.modal-backdrop').forEach(el => {
                    el.style.zIndex = '1040';
                });
            } catch (_) { }
        }

        // 在模态框中添加一行产品（可传入默认值）
        function addModalItemRow(item) {
            const tbody = document.querySelector('#modalPlanItemsTable tbody');
            const tr = document.createElement('tr');
            const data = item || {};
            if (data.id) { tr.dataset.itemId = data.id; }
            tr.innerHTML = `
                    <td>
                        <input type="text" class="form-control form-control-sm" placeholder="产品编号" value="${data.productCode ? data.productCode : ''}">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" placeholder="产品名称" value="${data.productName ? data.productName : ''}">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" placeholder="规格" value="${data.spec ? data.spec : ''}">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" placeholder="单位" value="${data.unit ? data.unit : ''}">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" placeholder="生产人员" value="${data.producer ? data.producer : ''}">
                    </td>
                    <td>
                        <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeModalItemRow(this)"><i class="fas fa-trash"></i></button>
                    </td>
                `;
            tbody.appendChild(tr);
        }

        // 删除模态框中的一行产品
        function removeModalItemRow(btn) {
            const tbody = document.querySelector('#modalPlanItemsTable tbody');
            if (tbody.children.length > 1) {
                btn.closest('tr').remove();
            } else {
                alert('至少需要保留一行产品数据');
            }
        }

        // 保存计划（示例：提交至后端更新接口）
        async function savePlanModal() {
            try {
                const planId = parseInt(document.getElementById('modalPlanId').value, 10);
                const code = document.getElementById('modalPlanCode').value.trim();
                const remark = document.getElementById('modalRemark').value.trim();

                const tbodyRows = Array.from(document.querySelectorAll('#modalPlanItemsTable tbody tr'));
                const products = [];
                for (const tr of tbodyRows) {
                    const [productCodeInput, productNameInput, specInput, unitInput, producerInput] = tr.querySelectorAll('input');
                    const productCode = productCodeInput.value.trim();
                    const productName = productNameInput.value.trim();
                    const spec = specInput.value.trim();
                    const unit = unitInput.value.trim();
                    const producer = producerInput.value.trim();
                    if (!productCode || !productName) {
                        alert('请完整填写产品信息（产品编号、产品名称为必填项）');
                        return;
                    }
                    const today = new Date();
                    const tomorrow = new Date();
                    tomorrow.setDate(today.getDate() + 1);

                    products.push({
                        id: tr.dataset.itemId ? parseInt(tr.dataset.itemId, 10) : 0,
                        productCode: productCode,
                        productName: productName,
                        spec: spec || null,
                        unit: unit || null,
                        producer: producer || null,
                        productionStartTime: today.toISOString(),
                        productionEndTime: tomorrow.toISOString(),
                        isRemoved: false
                    });
                }

                const payload = { id: planId, code: code, remark: remark || null, operateBy: "系统管理员", products: products };

                // 保存按钮loading
                const btn = event && event.target ? event.target : document.querySelector('#planDetailModal .btn-success');
                if (btn) { btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...'; }

                const resp = await fetch('/Plan/SavePlan', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload)
                });

                let result = { success: false };
                try { result = await resp.json(); } catch (_) { }

                if (result && (result.code === 200 || result.success)) {
                    alert('保存成功！');
                    closePlanModal();
                    // 刷新以看到最新数据
                    location.reload();
                } else {
                    alert('保存失败：' + (result.msg || result.message || '未知错误'));
                }
            } catch (err) {
                console.error('保存失败:', err);
                alert('保存失败：网络或脚本错误');
            } finally {
                const btn = document.querySelector('#planDetailModal .btn-success');
                if (btn) { btn.disabled = false; btn.innerHTML = '<i class="fas fa-save"></i> 保存'; }
            }
        }
    </script>
}